package com.ruoyi.system.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.NumberUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.ruoyi.common.config.QiNiuConfig;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.system.domain.*;
import com.ruoyi.system.service.IMedPoService;
import com.ruoyi.system.service.IMedicineService;
import lombok.RequiredArgsConstructor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.service.IPurchaseOrderService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;

/**
 * 采购管理Controller
 *
 * @author yangxp
 * @date 2020-07-31
 */
@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/medicine/purchaseOrder")
public class PurchaseOrderController extends BaseController {

	private final IPurchaseOrderService iPurchaseOrderService;

	private final IMedicineService medicineService;
	private final IMedPoService medPoService;

	/**
	 * 查询采购管理列表
	 */
	@PreAuthorize("@ss.hasPermi('medicine:purchaseOrder:list')")
	@GetMapping("/list")
	public TableDataInfo list(PurchaseOrder purchaseOrder) {
		startPage();
		LambdaQueryWrapper<PurchaseOrder> lqw = new LambdaQueryWrapper<PurchaseOrder>();
		if (StringUtils.isNotBlank(purchaseOrder.getPurchaser())) {
			lqw.eq(PurchaseOrder::getPurchaser, purchaseOrder.getPurchaser());
		}
		if (purchaseOrder.getPoDatetime() != null) {
			lqw.eq(PurchaseOrder::getPoDatetime, purchaseOrder.getPoDatetime());
		}
		List<PurchaseOrder> list = iPurchaseOrderService.list(lqw);
		QiNiuConfig qiNiuConfig = new QiNiuConfig();
		String cdn = qiNiuConfig.getCdn();
		list.forEach(item -> {
			String imageUrl = item.getPoImageUrl();
			JSONArray urlArray = JSON.parseArray(imageUrl);
			List<String> urlList = urlArray.stream().map(key -> "http://"+cdn + "/" + key).collect(Collectors.toList());
			item.setPoImageUrl(JSON.toJSONString(urlList));
		});

		return getDataTable(list);
	}

	/**
	 * 导出采购管理列表
	 */
	@PreAuthorize("@ss.hasPermi('medicine:purchaseOrder:export')")
	@Log(title = "采购管理", businessType = BusinessType.EXPORT)
	@GetMapping("/export")
	public AjaxResult export(PurchaseOrder purchaseOrder) {
		LambdaQueryWrapper<PurchaseOrder> lqw = new LambdaQueryWrapper<PurchaseOrder>(purchaseOrder);
		List<PurchaseOrder> list = iPurchaseOrderService.list(lqw);
		ExcelUtil<PurchaseOrder> util = new ExcelUtil<PurchaseOrder>(PurchaseOrder.class);
		return util.exportExcel(list, "purchaseOrder");
	}

	/**
	 * 获取采购管理详细信息
	 */
	@PreAuthorize("@ss.hasPermi('medicine:purchaseOrder:query')")
	@GetMapping(value = "/{id}")
	public AjaxResult getInfo(@PathVariable("id") Long id) {
		PurchaseOrder purchaseOrder = iPurchaseOrderService.getById(id);
		List<MedPo> medicineList = medPoService.list(new LambdaQueryWrapper<MedPo>().eq(MedPo::getPoId, purchaseOrder.getPoId()));
		purchaseOrder.setMedicineList(medicineList);
		return AjaxResult.success(purchaseOrder);
	}

	/**
	 * 新增采购管理
	 */
	@PreAuthorize("@ss.hasPermi('medicine:purchaseOrder:add')")
	@Log(title = "采购管理", businessType = BusinessType.INSERT)
	@PostMapping
	public AjaxResult add(@RequestBody PurchaseOrder purchaseOrder) {

		List<MedPo> medicineList = purchaseOrder.getMedicineList();
		//根据medId去重

		//Collectors.collectingAndThen(W,M) 返回一个收集器
		// W：要转换的收集器 M：转换函数
		ArrayList<MedPo> list = medicineList.stream().collect(
				Collectors.collectingAndThen(
						Collectors.toCollection(() -> new TreeSet<>(Comparator.comparing(MedPo::getMedId))),
						ArrayList::new)
		);

		//如果原清单的大小不等于去重后清单的大小,证明有重复元素被去重,则返回错误信息
		if (medicineList.size() != list.size()) {
			return AjaxResult.error("药品清单中有重复药品");
		}
		return toAjax(iPurchaseOrderService.savePurchaseOrder(purchaseOrder) ? 1 : 0);
	}

	/**
	 * 修改采购管理
	 */
	@PreAuthorize("@ss.hasPermi('medicine:purchaseOrder:edit')")
	@Log(title = "采购管理", businessType = BusinessType.UPDATE)
	@PutMapping
	public AjaxResult edit(@RequestBody PurchaseOrder purchaseOrder) {
		return toAjax(iPurchaseOrderService.updateById(purchaseOrder) ? 1 : 0);
	}

	/**
	 * 删除采购管理
	 */
	@PreAuthorize("@ss.hasPermi('medicine:purchaseOrder:remove')")
	@Log(title = "采购管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
	public AjaxResult remove(@PathVariable Long[] ids) {
		return toAjax(iPurchaseOrderService.removeByIds(Arrays.asList(ids)) ? 1 : 0);
	}

	@PostMapping("/costPrice")
	@PreAuthorize("@ss.hasPermi('medicine:purchaseOrder:query')")
	public AjaxResult getCostPrice(@RequestBody PurchaseOrder purchaseOrder) {
		List<MedPo> medicineList = purchaseOrder.getMedicineList();
		BigDecimal price = getCostPrice(medicineList);
		String formatPrice = NumberUtil.decimalFormat("#.##", price.doubleValue());
		return AjaxResult.success("获取成功", formatPrice);
	}

	/**
	 * 根基药品列表计算总价
	 *
	 * @param medicineList
	 * @return
	 */
	private BigDecimal getCostPrice(List<MedPo> medicineList) {
		BigDecimal price = new BigDecimal(0);
		for (MedPo item : medicineList) {
			//克数
			BigDecimal gram = NumberUtil.mul(item.getMedWeight(), 1000);
			LambdaQueryWrapper<Medicine> lqw = new LambdaQueryWrapper<>();
			Medicine medicine = medicineService.getOne(lqw.eq(Medicine::getMedId, item.getMedId()));
			//获取售价
			BigDecimal costPrice = medicine.getCostPrice();
			//获取每个售价
			BigDecimal one = NumberUtil.mul(costPrice, gram);
			//获取总价
			price = NumberUtil.add(price, one);
		}
		return price;
	}


}
